/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.tonyodev.fetchapp.ability;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.ability.fraction.FractionAbility;
import ohos.aafwk.ability.fraction.FractionManager;
import ohos.aafwk.ability.fraction.FractionScheduler;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.text.Font;
import ohos.agp.utils.Color;
import ohos.agp.window.dialog.ToastDialog;
import ohos.bundle.IBundleManager;

import com.tonyodev.fetch2.AbstractFetchListener;
import com.tonyodev.fetch2.Download;
import com.tonyodev.fetch2.Fetch;
import com.tonyodev.fetch2.FetchListener;
import com.tonyodev.fetch2.Request;
import com.tonyodev.fetchapp.Data;
import com.tonyodev.fetchapp.ProgressFraction;
import com.tonyodev.fetchapp.ResourceTable;
import com.tonyodev.fetchapp.snackbar.SnackBar;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;

import timber.log.Timber;

import static ohos.security.SystemPermission.WRITE_USER_STORAGE;

/**
 * @since 2021-05-20
 */
public class FragmentAbility extends FractionAbility {
    private static final int STORAGE_PERMISSION_CODE = 150;

    private Component rootView;
    private Fetch fetch;
    private ProgressFraction progressFraction1;
    private ProgressFraction progressFraction2;
    private Request request;

    private String TAG1 = "ProgressFraction1";
    private String TAG2 = "ProgressFraction2";

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        getWindow().setStatusBarColor(Color.getIntColor("#303f9f"));
        super.setUIContent(ResourceTable.Layout_ability_fragment_progress);
        rootView = findComponentById(ResourceTable.Id_rootView);
        fetch = Fetch.Impl.getDefaultInstance();

        FractionManager fractionManager = getFractionManager();

        progressFraction1 = new ProgressFraction();
        progressFraction2 = new ProgressFraction();

        Optional<Fraction> fractionByTag1 = fractionManager.getFractionByTag(TAG1);
        Optional<Fraction> fractionByTag2 = fractionManager.getFractionByTag(TAG2);
        FractionScheduler fractionScheduler = fractionManager.startFractionScheduler();
        if (fractionByTag1.isPresent() && fractionByTag1.get() != null) {
            fractionScheduler.remove(fractionByTag1.get());
        }
        if (fractionByTag1.isPresent() && fractionByTag2.get() != null) {
            fractionScheduler.remove(fractionByTag2.get());
        }
        fractionScheduler
            .add(ResourceTable.Id_fragment1, progressFraction1, TAG1)
            .add(ResourceTable.Id_fragment2, progressFraction2, TAG2)
            .submit();
        checkStoragePermissions();
    }

    private void checkStoragePermissions() {
        // 权限申请
        List<String> permissionsToRequest = new ArrayList<>();
        String[] permissions = new String[]{WRITE_USER_STORAGE};
        for (String permission : permissions) {
            if (verifyCallingPermission(permission) != IBundleManager.PERMISSION_GRANTED) {
                // 应用未被授予权限
                if (canRequestPermission(permission)) { // 是否可以申请弹框授权 如果可以就把权限添加到列表中
                    permissionsToRequest.add(permission);
                }
            }
        }

        if (!permissionsToRequest.isEmpty()) { //
            requestPermissionsFromUser(permissions, STORAGE_PERMISSION_CODE); // 说明有权限没有申请
        } else {
            enqueueDownload();
        }
    }

    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsFromUserResult(requestCode, permissions, grantResults);
        if (requestCode == STORAGE_PERMISSION_CODE) {
            enqueueDownload();
        } else {

            new SnackBar.Builder(FragmentAbility.this, rootView)
                .withMessage(getString(ResourceTable.String_permission_not_enabled))
                .show();

        }
    }

    private void enqueueDownload() {
        final String url = Data.sampleUrls[0];
        final String filePath = Data.getSaveDir(this) + "/fragments/movie.mp4";
        request = new Request(url, filePath);

        fetch.attachFetchObserversForDownload(request.getId(), progressFraction1, progressFraction2)
            .enqueue(request, updatedRequest -> {
                request = updatedRequest;
            }, error -> {
                Timber.d("FragmentActivity Error: %1$s", error.toString());
                new SnackBar.Builder(FragmentAbility.this, rootView)
                    .withMessage(getString(ResourceTable.String_enqueue_error))
                    .show();
            });
    }

    @Override
    protected void onActive() {
        super.onActive();
        fetch.addListener(fetchListener);
        if (request != null) {
            fetch.attachFetchObserversForDownload(request.getId(), progressFraction1, progressFraction2);
        }

    }

    @Override
    protected void onInactive() {
        super.onInactive();
        fetch.removeListener(fetchListener);
        if (request != null) {
            fetch.removeFetchObserversForDownload(request.getId(), progressFraction1, progressFraction2);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        fetch.close();
    }

    private final FetchListener fetchListener = new AbstractFetchListener() {

        @Override
        public void onQueued(Download download, boolean waitingOnNetwork) {

        }

        @Override
        public void onProgress(Download download, long etaInMilliSeconds, long downloadedBytesPerSecond) {
            if (request != null && request.getId() == download.getId()) {
                Timber.d("FragmentActivity id: %1$d, status: %2$s, progress: %3$d, error: %4$s", download.getId(), download.getStatus(), download.getProgress(), download.getError());
            }
        }


    };
}
